package com.zhentao.service.impl;


import com.zhentao.App.AppThreadLocalUtil;
import com.zhentao.model.es.dto.HistorySearchDto;

import com.zhentao.pojo.ApUserSearch;

import com.zhentao.schedule.file.model.user.pojo.ApUser;
import com.zhentao.schedule.model.common.dtos.ResponseResult;
import com.zhentao.schedule.model.common.enums.AppHttpCodeEnum;
import com.zhentao.service.ApUserSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //异步调用
    @Override
    public void insert(String keyword, Integer userId) {
        //1.查看当前用户搜索的关键词是否存在
        Query query = new Query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch =
                mongoTemplate.findOne(query, ApUserSearch.class, "ap_user_search");


        //2.如果存在，更新一下创建时间
        if (apUserSearch != null) {

            Update update = new Update().set("createdTime",new Date());
            mongoTemplate.updateFirst(query,update,ApUserSearch.class);
            return;
        }

        //3.如果不存在，判断当前历史记录的总条数是否大于10

        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        Query query1 = new Query(Criteria.where("userId").is(userId));
        //根据时间降序
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        System.out.println(apUserSearchList.size() + "size");
        if (apUserSearchList == null || apUserSearchList.size() < 10) {
            //如果没有或者小于10条，新增
            mongoTemplate.save(userSearch);
        } else { //已经有10条了，把最后一条替换掉

            ApUserSearch lastSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(lastSearch.getId())), userSearch);

        }
    }
    /**
     * 查询搜索历史
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        //获取当前用户
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //根据用户查询数据，按照时间倒序
        List<ApUserSearch> apUserSearches = mongoTemplate.find(Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 删除历史记录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto dto) {
        //1.检查参数
        if(dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2.判断是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //3.删除
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(user.getId()).and("id").is(dto.getId())),ApUserSearch.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
